'''
Created on Apr 8, 2011

@author: diego
'''


from _tests.test_games import GameTest
from juegos._agents import  AlphaBetaAgent, Agent
from juegos._base import Game
from juegos._utils import resultado
from utils import *

class Five_field_kono(Game):
    
    PLAYERS = (BLANCAS,NEGRAS)
    
    def __init__(self, board=None, enabled = 0, chips_per_player=7, empty_spaces=11):
        Game.__init__(self,*Five_field_kono.PLAYERS)
        if board:
            self.board = board #si ya viene el tablero armado
            setGlobalBoard(self.board)
        else:
            self.board = iniciarTablero()
            setGlobalBoard(self.board)
        self.enabled = enabled
        self.chips_per_player = chips_per_player

            
    def moves(self):
        if self.results(): # In order to avoid returning both moves and results.
            return None
        moves = obtenerPosiblesMovimientosJugador(enabled_map[self.enabled], self.board) 
        return {self.players[self.enabled]:moves}
    
    def next(self,**moves):        
        enabled_player = self.players[self.enabled]
        move = moves[enabled_player]
        nuevoTablero = hacerMovimiento(self.board, move, enabled_player)                             
        return Five_field_kono(nuevoTablero, (self.enabled + 1)% 2)
                        
    def results(self):        
        '''Este metodo retorna si un jugador gano la partida, 
            con un diccionario Jugador:Resultado, 
            o si todavia nadie ha ganado la partida.'''
        if verificarGano(NEGRAS, self.board):
            return resultado(BLANCAS,self.players,-1) 
            '''resultado(ganador,listaJugadores,resultado)'''
        elif verificarGano(BLANCAS, self.board):            
            return resultado(NEGRAS,self.players,-1)
        
        if config.cantidad_jugadas_index >= config.cota_cantidad_jugadas:
            print "limite de jugadas excedido"
            return resultado(NEGRAS,self.players,0)
        
        if obtenerPosiblesMovimientosJugador(obtenerOponente(NEGRAS), self.board).__len__()==0:
            return resultado(NEGRAS,self.players,0)
        
        if obtenerPosiblesMovimientosJugador(obtenerOponente(BLANCAS), self.board).__len__()==0:
            return resultado(NEGRAS,self.players,0)
        
        return None
    
    
             
    def testBlancasGanan(self):
        for i in range(filas):
            self.board[0][i] = BLANCAS
            self.board[1][i] = 0  
            self.board[2][i] = 0  
            self.board[3][i] = 0    
            self.board[4][i] = NEGRAS
        self.board[1][0] = BLANCAS
        self.board[1][4] = BLANCAS
        self.board[2][2] = NEGRAS
        self.board[3][3] = NEGRAS 
        
        
    def __str__(self):
        return 'five field kono'
    
    def __repr__(self):
        return '%s[%s]' % (self.players[self.enabled][0], self.board) 
       
        
        
class Test_Five_Field_Kono(GameTest):
    ''' Five field kono testcases
    '''
    def test_basic(self):
        self.basic_test(Five_field_kono, zero_sum=True, enabled_players=0)
    

INFINITE = 0x7FFFFFFF
class FiveFieldKonoMiniMaxAgent(AlphaBetaAgent):

    def match_moves(self, game, **moves):
        config.cantidad_jugadas_index += 1
    
    def match_begins(self, player, game):
        config.cantidad_jugadas_index = 0
        AlphaBetaAgent.match_begins(self, player, game)
        self.game = game
        
    def match_ends(self, game):
        self.game = game

    def __init_(self, name="FiveFieldKonoMiniMax", horizon=3, random=None, heuristic=None):
        AlphaBetaAgent.__init__(self, name, horizon, random, heuristic)
    
    def _minimax(self, game, depth, alpha=-INFINITE, beta=INFINITE):
        printTableroHTML(game.board, "minimax.html", sleepTime =0)
        #print "\t"*(-1 + depth), "->", fichasReverse[enabled_map[game.enabled]]
        return AlphaBetaAgent._minimax(self, game, depth)

if __name__ == '__main__':
    from juegos._agents import RandomAgent, FileAgent, MiniMaxAgent, AlphaBetaAgent
    from juegos._base import run_match, match 
    from heuristicas import  *   
    from utils import *
    rnd = random.Random()
    heuristica = heuristic_wrap([40,30,20,10,5])
    agenteEvaluador = FiveFieldKonoMiniMaxAgent('MiniMaxAgent_%05d' % 1, 3, rnd,heuristic=heuristica.heuristicaDistanciaDestino)
    for move_number, moves, game_state in match(Five_field_kono(),agenteEvaluador,RandomAgent(rnd, 'RandomAgent_%05d')  ):             
        if move_number is not None:
            print '%d: %s -> %r' % (move_number, moves, game_state)
        else:
            print 'Result: %s' % (moves)
            print 'Final board: %r'  % (game_state)

    
    
                
    
        
        
        
        